<?php


namespace app\api\controller\Course;


use app\api\controller\AppController;
use app\api\model\Coupon\CouponModel;
use app\api\model\Course\CourseCateModel;
use app\api\model\Course\CourseCollage;
use app\api\model\Course\CourseGroup;
use app\api\model\Course\CourseModel;
use app\api\model\Order\OrderModel;
use app\api\model\User\UserCouponModel;
use app\api\model\User\UserModel;
use app\Request;
use app\Utils\ImageUtil;
use app\Utils\Util;
use think\db\Where;
use think\facade\Db;
use xin\helper\Time;

class Course extends AppController
{
    /**
     * @api {get} /get_course_cate_more 课程分类
     * @apiGroup 课程
     * @apiSuccess {int} code 状态码 0：正常 -1：错误
     * @apiSuccess {json} data 数据源
     * @apiSuccess {string} msg 描述
     * @apiVersion 1.0.0
     */
    public function getCourseCateMore(Request $request)
    {
        $list = [
            [
                'id' => 0,
                'cate_name' => "推荐"
            ]
        ];
        $data = CourseCateModel::getCourseCateWhereMore([['is_show', '=', 1]]);
        foreach ($data as $item) {
            $arr['id'] = $item['id'];
            $arr['cate_name'] = $item['cate_name'];
            array_push($list, $arr);
        }
        return Util::returnJson(self::CODE_SUCCESS, $list);
    }

    /**
     * @api {get} /get_course_list 课程列表
     * @apiGroup 课程
     * @apiParam {int} page 页码
     * @apiParam {int} limit 数据条数
     * @apiParam {string} title 搜索标题
     * @apiParam {int} cate_id 分类ID 不传 默认查询推荐
     * @apiParam {int} school_id 学校ID
     * @apiParam {int} area_id 区域ID
     * @apiSuccess {int} code 状态码 0：正常 -1：错误
     * @apiSuccess {json} data 数据源
     * @apiSuccessExample {json} 部分数据
     * {
     *   "is_level":"1是否会员领取","label":"1：课程，2：商品","attr":" 1：立减 2：满减券 3：立减折扣 4：满减折扣","type":"1：全场 2：指定商品"
     * }
     * @apiSuccess {string} msg 描述
     * @apiVersion 1.0.0
     */
    public function getCourseList(Request $request)
    {
        $param = $request->param();
        $where = [
            ['c.is_show', '=', 1],
            ['c.is_del', '=', 0]
        ];
        $page = !empty($param['page']) ? $param['page'] : 1;
        $limit = !empty($param['limit']) ? $param['limit'] : 10;
        $title = !empty($param['title']) ? $param['title'] : "";
        $cate_id = isset($param['cate_id']) ? $param['cate_id'] : "";
        $school_id = !empty($param['school_id']) ? $param['school_id'] : 0;
        $area_id = !empty($param['area_id']) ? $param['area_id'] : 0;
        if (!empty($title)) {
            array_push($where, ['c.title', 'like', '%' . $title . '%']);
        }
        if (!empty($school_id)) {
            array_push($where, ['c.school_id', '=', $school_id]);
        }
        if (!empty($area_id)) {
            array_push($where, ['s.area_id', '=', $area_id]);
        }
        if (isset($cate_id)) {
            if ($cate_id == 0) {
                array_push($where, ['c.is_recommend', '=', 1]);
            } else {
                array_push($where, ['ccr.cate_id', '=', $cate_id]);
            }
        }
        $list = CourseModel::getCourseListWhere($page, $limit, $where, "c.id,c.title,c.img,c.teacher_brief,c.brief,c.price,c.cost_price,c.is_group,c.vip_price,c.school_id,c.start_time,c.end_time,sa.area_name,cc.cate_name");
        $count = CourseModel::getCourseCountWhere($where);
        foreach ($list as &$item) {
            $item['img'] = ImageUtil::i()->replaceUrl($item['img']);
            /*$images = !empty($item['slider_img']) ? json_decode($item['slider_img'],true) : [];
            foreach ($images as &$image){
                $image = ImageUtil::i()->replaceUrl($image);
            }
            $item['slider_img'] = $images;
            $item['details'] = !empty($item['details']) ? htmlspecialchars_decode($item['details']) : "";*/

            //相关优惠券
            $cou_where = [
                ['label', '=', 1],
                ['is_show', '=', 1],
                ['goods_ids', 'like', '%' . $item['id'] . ',' . '%'],
                ['start_time', '<', date("Y-m-d H:i:s", time())],
                ['end_time', '>', date("Y-m-d H:i:s", time())]
            ];
            $cou_where_1 = [
                ['label', '=', 1],
                ['is_show', '=', 1],
                ['type', '=', 1],
                ['start_time', '<', date("Y-m-d H:i:s", time())],
                ['end_time', '>', date("Y-m-d H:i:s", time())]
            ];
            $coupon_list = CouponModel::getCouponWhereOrMore([$cou_where, $cou_where_1], "id,coupon_title,is_level,label,attr,type,amount,total_amount");
            $item['coupon_list'] = !empty($coupon_list) ? $coupon_list : [];

            //总报名人数
            $or_where = [
                ['o.type', '=', 3],
                ['og.type', '=', 3],
                ['o.status', '<>', 4],
                ['o.status', '<>', -1],
                ['og.goods_id', '=', $item['id']],
                ['o.add_time', '>=', $item['start_time']],
                ['o.add_time', '<=', $item['end_time']],
            ];
            $item['course_all_count'] = count(OrderModel::getOrderWhereJoinMore($or_where));
        }
        return Util::returnPageJson(self::CODE_SUCCESS, $count, $list, "");
    }

    /**
     * @api {get} /get_course_info 课程详情
     * @apiGroup 课程
     * @apiParam {int} id 课程ID
     * @apiSuccess {int} code 状态码 0：正常 -1：错误
     * @apiSuccess {json} data 数据源
     * @apiSuccess {string} msg 描述
     * @apiSuccessExample {json} 部分数据
     * {
     *   "id":"课程ID",
     *   "title":"课程标题",
     *   "img":"图片",
     *   "teacher_brief":"老师简介",
     *   "brief":"课程简介",
     *   "slider_img":"图片数组",
     *   "details":"详情",
     *   "price":"价格",
     *   "cost_price":"成本价",
     *   "vip_price":"VIP价",
     *   "school_id":"学校ID",
     *   "coupon_list":{
     *          "id":"优惠券ID",
     *          "coupon_title":"优惠券ID",
     *          "is_level":"0：所有用户可领取 1： 会员领取",
     *          "label":"类型 1：课程，2：商品",
     *          "mer_id":"商家或者学校ID",
     *          "attr":"属性 1：立减 2：满减券 3：立减折扣 4：满减折扣",
     *          "type":"类型 1：全场 2：指定商品",
     *          "goods_ids":"商品或课程IDs",
     *          "amount":"抵扣价",
     *          "total_amount":"满减价",
     *          "is_infinite":"是否不限数量 0：限数量 1：不限数量",
     *          "total_num":"总数量",
     *          "receive_num":"已领取数量",
     *          "start_time":"开始时间",
     *          "end_time":"结束时间",
     *          "is_user":"用户是否领取 0：没有 1：已领取",
     *      }
     * }
     * @apiVersion 1.0.0
     */
    public function getCourseInfo(Request $request)
    {
        $param = $request->param();
        //  $course = CourseModel::getCourseWhere([['id', '=', $param['id']]], 'id,title,img,teacher_brief,brief,slider_img,details,price,cost_price,vip_price,school_id,start_time,end_time,deposit,brief_group');
        $course = $this->couser_get_info($param['id']);
        if (!$course) return Util::returnJson(self::CODE_ERROR, [], "课程不存在");
        $course['img'] = ImageUtil::i()->replaceUrl($course['img']);
        $images = !empty($course['slider_img']) ? json_decode($course['slider_img'], true) : [];
        foreach ($images as &$image) {
            $image = ImageUtil::i()->replaceUrl($image);
        }
        $course['slider_img'] = $images;
        $course['details'] = !empty($course['details']) ? htmlspecialchars_decode($course['details']) : "";

        //获取相关课程优惠券
        $cou_where = [
            ['label', '=', 1],
            ['is_show', '=', 1],
            ['goods_ids', 'like', '%' . $course['id'] . ',' . '%'],
            ['start_time', '<', date("Y-m-d H:i:s", time())],
            ['end_time', '>', date("Y-m-d H:i:s", time())]
        ];
        $cou_where_1 = [
            ['label', '=', 1],
            ['is_show', '=', 1],
            ['type', '=', 1],
            ['start_time', '<', date("Y-m-d H:i:s", time())],
            ['end_time', '>', date("Y-m-d H:i:s", time())]
        ];
        $coupon_list = CouponModel::getCouponWhereOrMore([$cou_where, $cou_where_1], 'id,coupon_title,is_level,label,mer_id,attr,type,goods_ids,amount,total_amount,is_infinite,total_num,receive_num,start_time,end_time');
        $course['coupon_list'] = !empty($coupon_list) ? $coupon_list : [];
        try {
            foreach ($course['coupon_list'] as &$item) {
                if (!empty($this->user)) {
                    $count = UserCouponModel::getUserCouponCountWhere([['uid', '=', $this->user['id']], ['coupon_id', '=', $item['id']]]);
                    if ($count) {
                        //用户已领取
                        $item['is_user'] = 1;
                    } else {
                        $item['is_user'] = 0;
                    }
                } else {
                    $item['is_user'] = 0;
                }
            }
            unset($item);
        } catch (\Exception $exception) {
            $item['is_user'] = 0;
        }

        //总报名人数
        $or_where = [
            ['o.type', '=', 3],
            ['og.type', '=', 3],
            ['o.status', '<>', 4],
            ['o.status', '<>', -1],
            ['og.goods_id', '=', $param['id']],
            ['o.add_time', '>=', $course['start_time']],
            ['o.add_time', '<=', $course['end_time']],
        ];
        $course['course_all_count'] = count(OrderModel::getOrderWhereJoinMore($or_where));

        return Util::returnJson(self::CODE_SUCCESS, $course, "");
    }

    /**
     * @param int $id
     * @return array|null|\think\Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 拼团附表
     */
    public function group_course(int $id)
    {
        return CourseGroup::where('course_id', $id)
            ->field('brief,details,group_price,start_time,end_time,group_num,count,deposit')->with(['course' => function ($query) {
                $query->field('id');
            }])->find();
    }

    /**
     * @param int $id
     * @return array|null|\think\Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundExcept
     * 课程详情
     */
    public function couser_get_info(int $id)
    {
        $info = CourseModel::where('id', $id)
            ->field('id,title,img,teacher_brief,brief,slider_img,price,cost_price,vip_price,school_id,start_time,end_time,deposit,brief_group,mer_id,is_group,group_num')
            ->with(['merchant' => function ($query) {
                return $query->field('id,account,mer_name as nickname');
            }])->find();
        $user_id = $info['merchant'] ? $info['merchant']['user_id'] : 0;
        $info['user'] = UserModel::where('id', $user_id)->field('mobile,head_img,nickname')->find(); //老师用户信息
        $info['student'] = CourseCollage::where('course_id', $id)->field('id,course_id,user_id')->with(['user' => function ($query) {
            $query->field('id,account,head_img,nickname');
        }])->select(); //报名学生列表
        $count = CourseCollage::where('course_id', $id)->with(['user'])->count(); //已报名学生统计
        $info['count'] = $count;
        $info['up_status'] = $this->status($count, $info['start_time'], $info['end_time'], $info['group_num']);
        return $info;
    }

    /**
     * @param $count 报名总人数
     * @param $start_time 报名开始时间
     * @param $end_time 报名结束时间
     * @param $group_num 拼团总人数
     */
    public function status(int $count, $start_time, $end_time, $group_num): bool
    {
        $bb = $this->rangeTime($start_time, $end_time);
        if ($bb !== true) return false;
        if ($count < $group_num) {

            return true;
        }
        return false;
    }

    /**
     * @param $startTime
     * @param $endTime
     * @return bool
     * 判断一个时间段是否在当前时间内
     */
    public function rangeTime($startTime, $endTime): bool
    {
        $date = date("Y-m-d", time());
        if (strtotime($date) >= strtotime($startTime) &&
            strtotime($date) <= strtotime($endTime)) {
            return true;
        }
        return false;
    }

}